package Array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class item15 {
    public  static List<List<Integer>> threeSum(int[] nums) {
        if (nums.length < 3 || nums == null) {
            return new ArrayList();
        }
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                break;
            }
            if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
            int L = i + 1;
            int R = nums.length - 1;
            while (L < R) {
                int sum = nums[i] + nums[L] + nums[R];
                if (0 == sum) {
                    res.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    while (L<R&&nums[L]==nums[L+1])L++;
                    while (L<R&&nums[R]==nums[R-1])R--;
                    L++;
                    R--;
                }
                else if(sum<0)
                {
                    L++;
                }
                else if(sum>0){
                    R--;
                }
            }
        }
        return res;
    }
    public void reBack(List<List<Integer>> combinations, List<Integer> track,int[] nums)
    {
        if(track.size()==3)
        {
            int count =0;
            for (int i = 0; i <track.size() ; i++) {
               count = count + track.get(i);
            }
            if(count==0) {
                combinations.add(track);
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if(track.contains(nums[i]))
            {
                continue;
            }
            track.add(nums[i]);
            reBack(combinations,track,nums);
            track.remove(track.size()-1);
        }
    }

    public static void main(String[] args) {
        int []nums= {-2,0,3,-1,4,0,3,4,1,1,1,-3,-5,4,0};
        List<List<Integer>> lists = threeSum(nums);
        System.out.println(lists);
    }
}
